package com.heima.wemedia.filter;

import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.pojos.WmUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @Author XHui
 * @Since 2024/2/6 18:11
 * @Version 1.0
 */
@Component
@WebFilter(value = "wmTokenFilter", urlPatterns = "/*")
@Order(-1)
@Slf4j
public class WmTokenFilter extends GenericFilterBean {

    /**
     * DO 过滤器
     *
     * @param servletRequest
     * @param servletResponse Servlet 响应
     * @param filterChain     过滤链
     * @throws IOException      ioexception
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain)
            throws IOException, ServletException {
        // 尝试获取请求头中的userId,
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String userId = httpServletRequest.getHeader("userId");

        // 将userId封装为WmUser对象，存入到ThreadLocal中去
        if (StringUtils.isNotBlank(userId)) {
            WmUser wmUser = new WmUser();
            wmUser.setId(Integer.valueOf(userId));
            WmThreadLocalUtils.setUser(wmUser);
        }
        // 放行请求
        filterChain.doFilter(servletRequest, servletResponse);
        // 请求完毕之后，需要清空threadLocal中信息, 避免当前线程被再次利用时，threadLocal中还有值
        WmThreadLocalUtils.clear();
    }
}
